﻿using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using RoadFlow.Utility;

namespace RoadFlow.Mvc
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            Config.InitUserPassword = Configuration.GetSection("InitUserPassword").Value;
            Config.IsDebug = "1".Equals(Configuration.GetSection("IsDebug").Value);
            Config.DebugUserId = Configuration.GetSection("DebugUserId").Value;
            Config.SingleLogin = "1".Equals(Configuration.GetSection("SingleLogin").Value);
            Config.ShowError = Configuration.GetSection("ShowError").Value.ToInt(0);
            Config.FilePath = Configuration.GetSection("FilePath").Value.TrimEnd('/').TrimEnd('\\');
            Config.DatabaseType = Configuration.GetSection("DatabaseType").Value.ToLower();
            Config.ConnectionString_SqlServer = Configuration.GetConnectionString("RF_SqlServer");
            Config.ConnectionString_MySql = Configuration.GetConnectionString("RF_MySql");
            Config.ConnectionString_Oracle = Configuration.GetConnectionString("RF_Oracle");
            var enterpriseWeiXin = Configuration.GetSection("EnterpriseWeiXin");
            if (null != enterpriseWeiXin)
            {
                Config.Enterprise_WeiXin_AppId = enterpriseWeiXin.GetSection("AppId").Value;
                Config.Enterprise_WeiXin_WebUrl = enterpriseWeiXin.GetSection("WebUrl").Value;
                Config.Enterprise_WeiXin_IsUse = "1".Equals(enterpriseWeiXin.GetSection("IsUse").Value);
            }
            var sessionConfig = Configuration.GetSection("Session");
            if (null != sessionConfig)
            {
                Config.UserIdSessionKey = sessionConfig.GetValue<string>("UserIdKey");
                Config.SessionTimeout = sessionConfig.GetValue<int>("TimeOut");
            }
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                //This lambda determines whether user consent for non - essential cookies is needed for a given request.
                //options.CheckConsentNeeded = context => true;
                //options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //设置表单可提交内容长度
            services.Configure<FormOptions>(options =>
            {
                options.ValueCountLimit = int.MaxValue;
                options.ValueLengthLimit = int.MaxValue;
                options.KeyLengthLimit = int.MaxValue;
                options.MultipartBodyLengthLimit = int.MaxValue;
                options.MultipartBoundaryLengthLimit = int.MaxValue;
            });

            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name = "RoadFlowCore.Session";
                options.IdleTimeout = TimeSpan.FromMinutes(Config.SessionTimeout);//设置session的过期时间
            });
            services.AddHttpContextAccessor();
            services.AddMemoryCache();
            services.AddTimedJob();//定时任务
           
            services.AddSignalR();
            //services.AddCors(options =>
            //{
            //    options.AddPolicy("SignalrCore",
            //        policy => policy.AllowAnyOrigin()
            //                        .AllowAnyHeader()
            //                        .AllowAnyMethod());
            //});
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp)
        {
            if (Config.ShowError == 1)
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticHttpContext();//使用Current.HttpContext
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();
            app.UseTimedJob();//使用TimedJob

            //app.UseCors("SignalrCore");
            app.UseSignalR(routes =>
            {
                routes.MapHub<Business.SignalR.SignalRHub>("/SignalRHub");
            });
            app.UseWebSockets();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "areas",
                  template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                );
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
